package ThreadCommunication.watnotify;

/**
 * @author dycong
 * @date 2018/5/5 19:20
 */
public class Account {
    private double balance;
    // 标识账户中是否已有存款
    private boolean flag = false;
    public Account(double balance){
        this.balance = balance;
    }

    synchronized public void draw(double drawAmount) {
        try {
            if (!flag) {
                // 当前线程等待，释放该同步监视器的锁定
                this.wait();
            } else {
                //执行取款操作
                System.out.println(Thread.currentThread().getName() + " 取钱：" + drawAmount);
                balance -= drawAmount;
                System.out.println("账户余额为：" + balance);
                // 账户中存款被取走，将标志flag设为false
                flag = false;
                // 唤醒其他线程
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized public void deposit(double depositAmount){
        try {
            if (flag){
                wait();
            }
            else {
                //执行存款操作
                System.out.println(Thread.currentThread().getName() + " 存款：" + depositAmount);
                balance += depositAmount;
                System.out.println("账户余额为：" + balance);
                // 账户中已有存款，将标志flag设为true
                flag = true;
                // 唤醒其他线程
                notifyAll();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
